package cn.elead.chaos.mybatils.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.elead.chaos.core.util.sql.SqlUtil;
import cn.elead.chaos.mybatils.web.page.PageDomain;
import cn.elead.chaos.mybatils.web.page.TableDataInfo;
import cn.elead.chaos.mybatils.web.page.TableSupport;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;

/**
 * web层通用数据处理
 * 
 * @author luopeng
 */
public class BaseController {

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	/**
	 * 设置请求分页数据
	 */
	protected void startPage() {
		PageDomain pageDomain = TableSupport.buildPageRequest();
		Integer pageNum = pageDomain.getPageNum();
		Integer pageSize = pageDomain.getPageSize();
		if (ObjectUtil.isNotNull(pageNum) && ObjectUtil.isNotNull(pageSize)) {
			String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
			PageHelper.startPage(pageNum, pageSize, orderBy);
		}
	}

	/**
	 * 响应请求分页数据
	 * @param <T>
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected <T> TableDataInfo<T> getDataTable(List<T> list) {
		TableDataInfo rspData = new TableDataInfo();
		rspData.setCode(HttpStatus.HTTP_OK);
		rspData.setRows(list);
		rspData.setTotal(new PageInfo(list).getTotal());
		return rspData;
	}
	
    /**
     * 页面跳转
     */
    public String redirect(String url)
    {
        return StrUtil.format("redirect:{}", url);
    }

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

}
